import type { App } from 'vue'
import { createPinia } from 'pinia'
import logger from '@/utils/logger'

export function setupStore(app: App) {
  const pinia = createPinia()
  
  // 添加持久化插件
  pinia.use(({ store }) => {
    // 自动保存重要状态到localStorage
    const importantStates = ['user', 'settings', 'theme']
    
    if (importantStates.includes(store.$id)) {
      // 恢复状态
      const saved = localStorage.getItem(`pinia-${store.$id}`)
      if (saved) {
        try {
          const data = JSON.parse(saved)
          store.$patch(data)
          logger.debug(`状态恢复: ${store.$id}`)
        } catch (error) {
          logger.error(`状态恢复失败: ${store.$id}`, error)
        }
      }
      
      // 监听状态变化
      store.$subscribe((mutation, state) => {
        try {
          localStorage.setItem(`pinia-${store.$id}`, JSON.stringify(state))
          logger.debug(`状态保存: ${store.$id}`)
        } catch (error) {
          logger.error(`状态保存失败: ${store.$id}`, error)
        }
      })
    }
  })
  
  app.use(pinia)
  logger.info('Pinia状态管理已初始化')
}

// 导出所有store
export * from './system'
export * from './user'
export * from './settings'